# -*- coding: utf-8 -*-
'''
Created on 29.Oca.2010

@author: Metehan
'''

import urllib, os, sys
import threading
import time

class Download(object):
    def __init__(self, url):
        self.say = 0
        self.url = url
        self.link = urllib.urlopen(self.url)
        self.info = self.link.info()
        self.urlname, self.downame = os.path.split(self.url)
        self.lock = threading.Condition()
        self.canceled = False

    def getSize(self):
        size = self.info.getheaders("Content-Length")[0]
        return int(size)

    def getName(self):
        return self.downame

    def getUrl(self):
        return self.urlname

    def download(self):
        if sys.platform == "win32":
            if os.path.isdir(os.getcwd()+"\\packages") == False:
                os.mkdir("packages")
            self.dosya = open(os.getcwd()+"\\packages\\"+self.downame, "wb")
        else:
            if os.path.isdir(os.getcwd()+"/packages") == False:
                os.mkdir("packages")
            self.dosya = open(os.getcwd()+"/packages/"+self.downame, "wb")
        
        size = self.getSize()
        while size>self.say and not self.canceled:
            self.lock.acquire()
            self.dosya.write(self.link.read(8192))
            self.say += 8192
            self.lock.release()
        self.dosya.close()
        self.say = self.getSize()

    def pause(self):
        self.lock.acquire()

    def resume(self):
        self.lock.release()

    def cancel(self):
        try:
            self.lock.release()
        except:
            pass
        self.canceled = True

class DownloadThread(threading.Thread, Download):
    def __init__(self, url):
        threading.Thread.__init__(self)
        Download.__init__(self, url)
        self.prevDown = 0
        self.prevTime = time.time()

    def percentage(self):
        return ((100.0 * self.say) / self.getSize())

    def run(self):
        self.download()

    def elapsedTime(self):
        currentTime = time.time()
        currentDown = self.say
        prevDown = self.prevDown
        prevTime = self.prevTime

        self.prevDown = currentDown
        self.prevTime = currentTime
        if(currentDown - prevDown == 0):
            return "-1:-1:-1"
        elp_sec = ((currentTime - prevTime) / (currentDown - prevDown)) * (self.getSize() - currentDown)

        hour = int(elp_sec) / 3600
        elp_sec = elp_sec % 3600
        minute = int(elp_sec) / 60
        elp_sec = elp_sec % 60
        sec = int(elp_sec)

        return "%.2d:%.2d:%.2d" % (hour, minute, sec)
